package one.stand.util;

import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class HttpUtil2 {
    public static final MediaType TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    private static OkHttpClient client = new OkHttpClient();

    public static String get(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static byte[] postBytes(String url, String json) {
        RequestBody body = RequestBody.create(TYPE_JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().bytes();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static String post(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(TYPE_JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try (Response response = client.newCall(request).execute()) {
            return response.body().string();
        }
    }

    public static String post(String url, Map<String, String> paramMap) {
        FormBody.Builder body = new FormBody.Builder();
        if (Objects.nonNull(paramMap)) {
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                body.add(entry.getKey(), entry.getValue());
            }
        }
        FormBody formBody = body.build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return StringUtils.EMPTY;
    }
}
